const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command
// 获取openId云函数入口函数
exports.main = async (event, context) => {
  // 获取基础信息
  let result = {}
  let userCards = []//用户卡片列表
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  let queryData = {}//插入数据时数据格式
  let now =new Date().getTime() //当前时间
  let parent_openid = ''//上级用户
  console.log(event);
  if (event.parent_openid) {
    parent_openid=event.parent_openid
  }
  console.log(parent_openid);
  // 拿活动信息
  let active = await db.collection('activity').doc(event.id).get()
  // 拿用户参与数据
  let user = await db.collection('users').where({activityID:event.id,openid:openid}).get()
  console.log(user.data);
  if (user.data.length === 0 &&active.data.endtime>now) {//判断活动未过期且无数据的用户随机3张卡片并插入数据库
    let cards = active.data.keywords.split('')
    let copyCards = [...cards] //深拷贝
    console.log('还未参加，随机生成3张卡片');
    for (let i = 0; i < 3; i++) {
      let random = Math.floor(Math.random()*cards.length)
      userCards.push(cards[random])
      cards.splice(random,1)
    }
    let tempArr = copyCards.map(item=>{
      return userCards.indexOf(item) != -1 ? 1 : 0
    })
    console.log(userCards,tempArr);
    
    queryData = {
    "activityID": event.id,
    "_createTime": now,
    "_updateTime": now,
    "cards": tempArr,
    "isjoin": false,
    "openid": openid,
    "count":5,//默认添加5次
    "parent_openid":parent_openid,
    "nickname":'',
    "headimg":''
    }
    await db.collection('users').add({data:queryData}).then(res=>{
      queryData["_id"] = res._id
    })
    //参与人数+1
    db.collection('activity').doc(event.id).update({data:{join:_.inc(1)}})

  }
  
  return {
    openid,
    active:active.data,
    user:user.data[0] || queryData
  }
}